<?

class Mojito_Model
{
	private static $_Loader=null;
	/**
	 * _defaultOptions
	 * 
	 * (default value: array('path'=>null,'dbAdapter'=>null,'prefix'=>''))
	 * 
	 * @var array
	 * @access private
	 */
	private static $_defaultOptions=array('path'=>null,'dbAdapter'=>null,'prefix'=>'','Log'=>null);
	
	/**
	 * _options
	 * 
	 * (default value: array())
	 * 
	 * @var array
	 * @access private
	 */
	private static $_options=array();
	
	/**
	 * modelInstances
	 * internally maintains singletons of models accessed via Mojito_Model::get()
	 * (default value: array())
	 * 
	 * @var array
	 * @access private
	 */
	private static $modelInstances=array();
	
	/**
	 * setOptions function.
	 * must be called before any call to get(). Bootstrap is a good place.
	 * @access public
	 * @static
	 * @param mixed array $options
	 * @return void
	 */
	public static function setOptions(array $options)
	{
		// TODO replace all this with a foreach that calls setters on each option
		self::$_options = array_merge(self::$_defaultOptions,$options);
		if (empty(self::$_options['path'])) throw new Mojito_Model_Exception('path option must be a string pointing to folder containing model scripts.');
		if (is_string(self::$_options['dbAdapter'])) self::$_options['dbAdapter']=Zend_Registry::get(self::$_options['dbAdapter']);
		if (empty(self::$_options['dbAdapter'])||!self::$_options['dbAdapter'] instanceof Zend_Db_Adapter_Abstract) throw new Mojito_Model_Exception('dbAdapter option must be an instance of Zend_Db_Adapter_Abstract');
	}
	
	/**
	 * get function.
	 * factory pattern to access models that extend Mojito_Model_Abstract
	 * @access public
	 * @static
	 * @param mixed $model
	 * @return void
	 */
	public static function get($model)
	{
		if (!self::$_Loader instanceof Zend_Loader_PluginLoader) self::$_Loader=new Zend_Loader_PluginLoader(array(self::$_options['prefix']=>self::$_options['path']),'Mojito_Model');
		$model=ucfirst($model);
		if (empty(self::$modelInstances[$model]))
		{
			$class=self::$_Loader->load($model);
			if ($class!==false)
			{
				$Model=new $class(self::$_options['dbAdapter']);
				if (!$Model instanceof Mojito_Model_Abstract) throw new Mojito_Model_Exception('Model \''.$class.'\' must extend Mojito_Model_Abstract');
				self::$modelInstances[$model] = $Model;
			}
		}
		return self::$modelInstances[$model];
	}
	
	public static function getDbAdapter()
	{
		return self::$_options['dbAdapter'];
	}
	
	public static function getLog()
	{
		return self::$_options['Log'];
	}
}